//
//  ScrollView.m
//  product_B
//
//  Created by lanou on 16/5/27.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "ScrollView.h"
#import <UIImageView+WebCache.h>
#import "ReadScrollViewModel.h"
@interface ScrollView()<UIScrollViewDelegate>
@property (nonatomic,strong)UIScrollView *scrollView;
@property (nonatomic,strong)UIPageControl *page;
@property (nonatomic,strong)NSTimer *timer;
@end

@implementation ScrollView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        _scrollView = [[UIScrollView alloc]initWithFrame:self.bounds];
        _scrollView.pagingEnabled = YES;
        _scrollView.delegate = self;
        [self addSubview:_scrollView];
        _page = [[UIPageControl alloc]initWithFrame:CGRectMake(0, frame.size.height- 30 , self.frame.size.width, 30)];
        [self addSubview:_page];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickScrollView:)];
        [_scrollView addGestureRecognizer:tap];
        
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
        
    }
    return self;
}
- (void)setImageWithImageArray:(NSMutableArray *)imageArray{
    if (imageArray.count == 0||imageArray == _imageArray) {
        return;
    }
    _imageArray = [NSMutableArray array];
    for (ReadScrollViewModel *model in imageArray) {
        [_imageArray addObject:model.cover];
    }
    _modelArray = imageArray;
    _scrollView.contentSize = CGSizeMake(self.frame.size.width * (_imageArray.count + 2), self.frame.size.height);
    for (UIView *v in _scrollView.subviews) {
        [v removeFromSuperview];
    }
    for (int i = 0; i < _imageArray.count + 2; i++) {
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(i * self.frame.size.width, 0, self.frame.size.width, self.frame.size.height)];
        NSInteger index = _imageArray.count - 1;
        if (i>0) {
            index = (i - 1) % _imageArray.count;
        }
        [imageView sd_setImageWithURL:[NSURL URLWithString:_imageArray[index]]];
        [_scrollView addSubview:imageView];
        
    }
    [_scrollView setContentOffset:CGPointMake(_scrollView.frame.size.width, 0) animated:NO];
    _page.numberOfPages = _imageArray.count;
}

- (void)clickScrollView:(UITapGestureRecognizer *)sender{
    if (_delegate && [_delegate respondsToSelector:@selector(clickedScrollViewWithIndex:)]) {
        [_delegate clickedScrollViewWithIndex:_page.currentPage];
    }
}
- (void)timerAction{
    [UIView animateWithDuration:0.4 animations:^{
        [_scrollView setContentOffset:CGPointMake(_scrollView.contentOffset.x + _scrollView.frame.size.width, 0) animated:NO];
    } completion:^(BOOL finished) {
        if (_scrollView.contentOffset.x == (_imageArray.count + 1) * _scrollView.frame.size.width) {
            [_scrollView setContentOffset:CGPointMake(_scrollView.frame.size.width * 1, 0) animated:NO];
        }
//        NSInteger index = _scrollView.contentOffset.x / _scrollView.frame.size.width - 1;
        _page.currentPage = _scrollView.contentOffset.x / _scrollView.frame.size.width - 0.5;
    }];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    //如果是第一张（数组最后一张），就让scrollView偏移到倒数第二张（还是数组最后一张）
    if (scrollView.contentOffset.x == 0) {
        [scrollView setContentOffset:CGPointMake(scrollView.frame.size.width * _imageArray.count, 0) animated:NO];
    }
    //如果是最后一张（数组第一张），就让scrollView偏移到第二张（还是数组第一张）
    if (scrollView.contentOffset.x == (_imageArray.count + 1) * scrollView.frame.size.width) {
        [scrollView setContentOffset:CGPointMake(scrollView.frame.size.width, 0) animated:NO];
    }
    
    _page.currentPage = scrollView.contentOffset.x / scrollView.frame.size.width - 0.5;

}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self stopTimer];
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self startTimer];
}

-(void) stopTimer{
    [self.timer invalidate];
    self.timer=nil;
}
-(void) startTimer{
    self.timer=[NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    
    [[NSRunLoop mainRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
}
@end
